<template>
  <div id="subscribe">
    <div v-if="showForm">
      <div class="subscribe-bg">
        <div v-if="msg">
          <i class="iconfont icon-iconfontgantanhao3"></i><p>{{msg}}</p>
        </div>
      </div>
      <div>
        <van-cell-group>
          <van-cell title="所在地区" isLink :value="area || '请选择'" @click="showAddress = true" />
          <van-cell title="学校类型" isLink :value="schoolsType.text || '请选择'" @click="handleShowSchoolsType" />
          <van-cell title="学校名称" isLink :value="schools.text || '请选择'" @click="handleShowSchools" />
          <van-cell title="所在年级" isLink :value="grade.text || '请选择'" @click="handleShowGrade" />
          <van-cell title="所在班级" isLink :value="classes.text || '请选择'" @click="handleShowClasses" />
          <van-cell title="疫苗种类" isLink :value="cartgory.title || '请选择'" @click="handleShowCartgory" />
          <van-cell title="接种地点" isLink :value="locations.title || '请选择'" @click="handleShowLocations" />
          <van-cell title="预约时间" isLink @click="handleShowDate">
            <span v-if="dateStr && timeStr">{{dateStr}} {{timeStr}}</span>
            <span v-else>请选择</span>
          </van-cell>
          <van-field
            v-model="realName"
            label="姓名"
            icon="clear"
            placeholder="请输入您的姓名"

            @click-icon="realName = ''"
          />
          <van-field
            v-model="tel"
            type="tel"
            :maxlength="11"
            label="手机号码"
            icon="clear"
            placeholder="请输入您的手机号码"

            @click-icon="tel = ''"
          />

        </van-cell-group>


        <div style="padding: 30px 10px;">
          <van-button
            :disabled="disabled"
            class="border-radius"
            size="normal"
            type="primary"
            block
            :loading="subLoading"
            @click="submit"
          >提交预约信息</van-button>
        </div>

      </div>
      <YmDatePicker
        v-model="showDate"
        :disabled-week-day="locations.invalid"
        :unix-time="locations.startDate"
        :hasChange="locations.id"
        @onConfirm="handleDateConfirm"
      ></YmDatePicker>



      <AreaPicker
        v-model="showAddress"
        @onConfirm="handleAreaCofirm"
      ></AreaPicker>

      <van-popup v-model="showSchoolsType" position="bottom" :close-on-click-overlay="false">
        <van-picker show-toolbar title="选择学校类型" @confirm="onSchoolsTypeConfirm" @cancel="showSchoolsType = false" :columns="schoolsTypeData" />
      </van-popup>

      <van-popup v-model="showSchools" position="bottom" :close-on-click-overlay="false">
        <van-picker show-toolbar title="选择学校" @confirm="onSchoolsConfirm" @cancel="showSchools = false" :columns="schoolsData" />
      </van-popup>
      <van-popup v-model="showGrade" position="bottom" :close-on-click-overlay="false">
        <van-picker show-toolbar title="选择年级" @confirm="onGradeConfirm" @cancel="showGrade = false" :columns="gradeData" />
      </van-popup>

      <van-popup v-model="showClasses" position="bottom" :close-on-click-overlay="false">
        <van-picker show-toolbar title="选择班级" @confirm="onClassesConfirm" @cancel="showClasses = false" :columns="classesData" />
      </van-popup>

      <van-popup v-model="showCartgory" position="bottom">
        <van-picker
          show-toolbar
          title="选择疫苗种类"
          valueKey="title"
          :columns="cartgoryColumns"
          @cancel="showCartgory = false"
          @confirm="onCartgoryConfirm"
        />
      </van-popup>

      <van-popup v-model="showLocations" position="bottom">
        <van-picker
          show-toolbar
          title="选择接种地点"
          valueKey="title"
          :columns="locationsColumns"
          @cancel="showLocations = false"
          @confirm="onLocationsConfirm"
        />
      </van-popup>

      <van-popup v-model="showTime" position="bottom">
        <van-picker
          show-toolbar
          title="选择预约时段"
          valueKey="label"
          :columns="currentTimeColumns"
          @cancel="showTime = false"
          @confirm="handleTimeConfirm"
        />
      </van-popup>

    </div>


    <div v-if="showDetails">
      <div class="subscribe-bg">
        <div>
          <i class="iconfont icon-iconfontgantanhao3"></i><p>预约成功</p>
        </div>
      </div>
      <van-cell-group>
        <van-cell title="所在地区" :value="dataItem.province + dataItem.city + dataItem.district" />
        <van-cell title="学校类型" :value="dataItem.schoolType" />
        <van-cell title="学校名称" :value="dataItem.school" />
        <van-cell title="所在年级" :value="dataItem.grade" />
        <van-cell title="所在班级" :value="dataItem.class" />

        <van-cell title="疫苗种类" :value="dataItem.vaccine" />
        <van-cell title="接种地点" :value="dataItem.location" />
        <van-cell title="预约时间">
          <span >{{dataItem.willDate}} {{dataItem.willDay == 1? '上午': '下午'}}</span>
        </van-cell>
        <van-cell title="姓名" :value="dataItem.realName" />
        <van-cell title="手机号码" :value="dataItem.mobile" />
      </van-cell-group>

      <div style="padding: 30px 10px;">
        <van-button
          :disabled="cancelDisabled"
          class="border-radius"
          size="normal"
          type="primary"
          block
          :loading="cancelDisabled"
          @click="handleCancelSubscribe"
        >取消预约</van-button>
      </div>
    </div>

  </div>
</template>

<script>
  import schema from 'async-validator'
  import { Picker, Popup } from "vant";
  import { unixTimestamp } from "@/libs/utils";
  import YmDatePicker from "@/components/YmDatePicker.vue"
  import AreaPicker from "@/components/AreaPicker.vue"
  const descriptor = {
    provinceId: {required: true, message: '请选择所在地区'},
    cityId: {required: true, message: '请选择所在地区'},
    districtId: {required: true, message: '请选择所在地区'},
    schoolTypeId: {required: true, message: '请选择学校类型', min: 1},
    schoolId: {required: true, message: '请选择学校', min: 1},
    gradeId: {required: true, message: '请选择年级', min: 1},
    classId: {required: true, message: '请选择班级', min: 1},
    vaccineId: {required: true, message: '请选择疫苗种类', min: 1},
    locationId: {required: true, message: '请选择接种地点', min: 1},
    date: {required: true, message: '请选择预约时间'},
    day: {required: true, message: '请选择预约时间'},
    realName: {required: true, message: '请填写姓名'},
    mobile: [
      {required: true, message: '请填写手机号码'},
      {validator: function (rule, value, callback, source, options) {
          var reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
          var errors = [];
          if(!reg.test(value)) {
            errors.push('请填写正确的手机号码')
          }
          callback(errors);
        }}
    ]
  }
  const validator = new schema(descriptor)

  export default {
    components: {
      [Picker.name]: Picker,
      [Popup.name]: Popup,
      YmDatePicker,
      AreaPicker,
    },
    computed: {
      locationsId() {
        return this.locations.id
      },
      schoolsTypeId() {
        return this.schoolsType.id
      },
      schoolsId() {
        return this.schools.id
      },
      classesId() {
        return this.classes.id
      },
      gradeId() {
        return this.grade.id
      },
    },
    created() {
      this.getDetails()
    },
    watch: {
      districtId: function (val) {
        if(val) {
          this.getLocations()
          this.getSchoolsData()
        }
        this.schoolsType = {
          id: 0,
          text: ''
        }
        this.schools = {
          id: 0,
          text: ''
        }
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      locationsId: function (val) {
        this.dateStr = ''
        this.timeStr = ''
        this.dateStrCache = ''
        this.timeAPm = ''
      },
      timeAPm: function(val) {
        if (val) {
          this.checkLimit()
        }
      },
      schoolsTypeId: function (val) {
        this.schools = {
          id: 0,
          text: ''
        }
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      schoolsId: function (val) {
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      gradeId: function (val) {
        this.classes = {
          id: 0,
          text: ''
        }
      },
    },
    data() {
      return {
        showSchoolsType: false, // 学校类型展示
        showSchools: false, // 学校展示
        showGrade: false, //年级展示
        showClasses: false, //班级展示
        schoolsTypeIndex: 0,
        schoolsTypeData: [], // 学校类型
        schoolsData: [], // 学校
        gradeData: [], //年级
        classesData: [], // 班级

        schoolsType: {
          id: '',
          text: ''
        },

        schools: {
          id: '',
          text: ''
        },

        grade: {
          id: '',
          text: ''
        },

        classes: {
          id: '',
          text: ''
        },


        cancelDisabled: false, //取消预约状态
        dataItem: {},
        showForm: false, // 显示表单
        showDetails: false, //显示详情
        msg: '',
        area: '', //省市区
        provinceId: '', //省id
        cityId: '', //市id
        districtId: '', //区域ID
        columns: [],
        answer: [],
        showCartgory: false,
        cartgory: {
          id: 0,
          title: ''
        },
        cartgoryColumns: [],
        locationsColumns: [],
        showLocations: false,
        locations: {
          id: 0,
          title: '',
          maxNum: 0,
          invalid: [],
          startDate: ''
        },
        showAddress: false,
        address: '',
        realName: '',
        tel: '',
        showDate: false,
        showTime: false,
        dateStr: '',
        dateStrCache: '',
        timeStr: '',
        timeAPm: '',
        currentTimeColumns: [
          {
            value: 1,
            label: '上午'
          },
          {
            value: 2,
            label: '下午'
          }
        ],
        disabled: false,
        subLoading: false
      };
    },
    methods: {
      //获取学校所有数据
      getSchoolsData() {
        this.$http('/api/common/school', {
          districtId: this.districtId
        }).then(data => {
          this.datas = data
          this.initSchoolsTypeData()
          this.initSchoolsData(0)
          this.initGradeData(0, 0)
          this.initClassesData(0, 0, 0)
        }).catch(err => {

        })
      },

      //初始化学校类型
      initSchoolsTypeData() {
        try {
          let schoolsTypeData = Array.from(this.datas, x => ({
            id: x.id,
            text: x.title
          }))
          this.schoolsTypeData = schoolsTypeData
        } catch (err) {
          
        }
      },

      //初始化学校
      initSchoolsData(index) {
        try {
          const schools = this.datas[index].schools
          let schoolsData = Array.from(schools, x => ({
            id: x.id,
            text: x.title
          }))
          this.schoolsData = schoolsData
        } catch (err) {

        }
      },

      //初始化班级
      initGradeData(index, idx) {
        try {
          const grade = this.datas[index].schools[idx].grade
          let gradeData = Array.from(grade, x => ({
            id: x.id,
            text: x.title
          }))
          this.gradeData = gradeData
        } catch (err) {

        }
      },

      initClassesData(index, idx, i) {
        try {
          const classes = this.datas[index].schools[idx].grade[i].classes
          let classesData = Array.from(classes, x => ({
            id: x.id,
            text: x.title
          }))
          this.classesData = classesData
        } catch (err) {

        }
      },

      //显示学校类型picker
      handleShowSchoolsType() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showSchoolsType = true
      },
      //学校类型picker确认
      onSchoolsTypeConfirm(val, index) {
        this.schoolsTypeIndex = index
        this.initSchoolsData(index)
        this.initGradeData(index, 0)
        this.initClassesData(index, 0, 0)
        this.schoolsType = val
        this.showSchoolsType = false
      },

      //显示学校picker
      handleShowSchools() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showSchools = true
      },
      //学校picker确认
      onSchoolsConfirm(val, index) {
        this.initGradeData(this.schoolsTypeIndex, index)
        this.initClassesData(this.schoolsTypeIndex, index, 0)
        this.schools = val
        this.showSchools = false
      },

      //显示年级picker
      handleShowGrade() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showGrade = true
      },

      //显示班级picker
      handleShowClasses() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showClasses = true
      },
      //年级picker确认
      onGradeConfirm(val, index) {
        this.grade = val
        this.initClassesData(this.schoolsTypeIndex, index, 0)
        this.showGrade = false
      },
      //班级picker确认
      onClassesConfirm(val) {
        this.classes = val
        this.showClasses = false
      },

      //拉去预约详情
      getDetails() {
        this.$http('/api/appointment/detail', { openId: window.localStorage.openId }).then(data => {
          if(data) {
            this.showDetails = true
            this.dataItem = data
            this.showForm = false
          }
        }).catch(err => {
          const { code, msg, data } = err
          if (code == -2) {
            this.showForm = true
            this.showDetails = false
          }
        })
      },
      //选择地区
      handleAreaCofirm(area) {
        this.area = Array.from(area, x => x.name).join(' ')
        this.provinceId = area[0].id
        this.cityId = area[1].id
        this.districtId = area[2].id
      },
      //获取接种地点
      getLocations() {
        this.$http('/api/common/locationsAndVaccines', {
          districtId: this.districtId
        }).then(data => {
          this.cartgoryColumns = data.vaccines
          this.cartgory = data.vaccines[0]
          // data.locations.map(item => {
          //   item.startDate = item.startDate
          // })
          this.locationsColumns = data.locations
          this.locations = {
            id: 0,
            title: '',
            maxNum: 0,
            invalid: [],
            startDate: ''
          }
        }).catch(err => {})
      },
      //显示疫苗种类选择框
      handleShowCartgory() {
        if (!this.districtId){
          this.$toast('请选择接种所在地区')
          return
        }
        this.showCartgory = true
      },
      //疫苗种类选择
      onCartgoryConfirm(e) {
        this.cartgory = e
        this.showCartgory = false
      },
      //显示接种地点选择框
      handleShowLocations() {
        if (!this.districtId){
          this.$toast('请选择接种所在地区')
          return
        }
        this.showLocations = true
      },
      //接种地点选择
      onLocationsConfirm(e) {
        this.locations = e
        this.showLocations = false
      },

      //显示预约时间
      handleShowDate() {
        if (!this.districtId){
          this.$toast('请选择接种所在地区')
          return
        }
        if (!this.locations.id){
          this.$toast('请选择接种地点')
          return
        }
        this.showDate = true
      },
      //年月日选择确认
      handleDateConfirm(value) {
        this.dateStrCache = value;
        this.showDate = false;
        this.$nextTick(() => {
          this.showTime = true;
        });
      },
      // 上午下午选择确认
      handleTimeConfirm(e) {
        this.timeStr = e.label;
        this.timeAPm = e.value;
        this.dateStr = this.dateStrCache;
        this.showTime = false;
      },
      //检查当天这时间段预约是否达到上限
      checkLimit() {
        this.$http('/api/appointment/checkLimit', {
          locationId: this.locations.id,
          date: this.dateStr,
          day: this.timeAPm
        }).then(data => {
          let disabled = false
          this.msg = ''
          if (data.count !== undefined) {
            if(data.count >= this.locations.maxNum) {
              this.$dialog.alert({
                title: '提示',
                message: '该预约点已超过预约上线，请重新选择预约时间'
              })
              this.msg = '该预约点已超过预约上线'
              this.dateStr = ''
              this.timeStr = ''
              this.timeAPm = ''
              this.dateStrCache = ''
              disabled = true
            }
          } else {
            disabled = true
          }
          this.disabled = disabled
        }).catch(err => {
          this.disabled = true
          this.$toast(err.msg)
        })
      },
      submit() {
        let req = {
          provinceId: this.provinceId,
          cityId: this.cityId,
          districtId: this.districtId,
          schoolTypeId: this.schoolsTypeId,
          schoolId: this.schoolsId,
          gradeId: this.gradeId,
          classId: this.classesId,
          vaccineId: this.cartgory.id,
          locationId: this.locations.id,
          date: this.dateStr,
          day: this.timeAPm,
          realName: this.realName,
          mobile: this.tel,
          openId: window.localStorage.openId,
        }
        validator.validate(req, (errors, fields) => {
          if(errors) {
            this.$toast(errors[0].message)
          } else {
            this.subLoading = true
            this.$toast.loading({
              mask: true,
              duration: 0,
              message: '正在预约...'
            })
            this.$http('/api/appointment/make', req).then(res => {
              this.$toast.success('预约成功')
              this.getDetails()
              this.initForm()
            }).catch(err => {
              this.subLoading = false
              this.$toast.fail(err.msg || '预约失败')
            })
          }
        })
      },

      //取消预约
      handleCancelSubscribe() {
        let that = this
        this.$dialog.confirm({
          title: '提示',
          message: '您确定要取消预约吗？'
        }).then(() => {
          this.cancelDisabled = true
          this.$toast.loading({
            mask: true,
            duration: 0,
            message: '取消预约中'
          })
          this.$http('/api/appointment/cancel', {
            openId: window.localStorage.openId,
            appointmentId: this.dataItem.id
          }).then(data => {
            this.$toast.success('预约已取消')
            this.showForm = true
            this.showDetails = false
          }).catch(err => {
            this.cancelDisabled = false
            this.$toast(err.msg || '取消失败')
          })
        }).catch(err => {
          this.cancelDisabled = false
        })
      },


      //初始化表单
      initForm() {
        this.cancelDisabled = false
        this.disabled = false
        this.subLoading = false
        this.area = ''//省市区
        this.provinceId = '' //省id
        this.cityId = '' //市id
        this.districtId = '' //区域ID
        this.dataItem = {}
        this.cartgory = {
          id: 0,
          title: ''
        }
        this.cartgoryColumns = []
        this.locationsColumns = [],
        this.locations = {
          id: 0,
          title: '',
          maxNum: 0,
          invalid: [],
          startDate: ''
        }
        this.address = ''
        this.realName = ''
        this.tel = ''
        this.dateStr = ''
        this.dateStrCache = ''
        this.timeStr = ''
        this.timeAPm = ''

        this.schoolsTypeIndex = 0
        this.schoolsTypeData = [] // 学校类型
        this.schoolsData = []// 学校
        this.classesData = [] // 班级
        this.gradeData = [] // 班级

        this.schoolsType = {
          id: '',
          text: ''
        }

        this.schools = {
          id: '',
          text: ''
        }

        this.classes = {
          id: '',
          text: ''
        }

        this.grade = {
          id: '',
          text: ''
        }
      }
    }
  };
</script>
<style scoped>
  .subscribe-bg{
    height: 77.5px;
    width: 100%;
    background: url('../../static/images/subscribe-bg.png') #54a42c;
    background-size: 100% 100%;
    color: #fff;
  }
  .subscribe-bg>div{
    height: 77.5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
